<?php
namespace Mouta\UserBundle\Handler;

use Mouta\AmistateBundle\Entity\Usuario;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Bundle\FrameworkBundle\Routing\Router;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\HttpFoundation\Session\Session;

class AuthenticationHandler
implements AuthenticationSuccessHandlerInterface,
           AuthenticationFailureHandlerInterface
{
    private $router;
    private $session;
    private $container;

    public function __construct(Router $router, Session $session, ContainerInterface $container)
    {
        $this->router = $router;
        $this->session = $session;
        $this->container = $container;
    }
    
    public function onAuthenticationSuccess(Request $request, TokenInterface $token)
    {
        $social = $token->getUser()->refreshFacebookPost($this->container->parameters['fos_facebook.app_id'], $this->container->parameters['fos_facebook.secret']);
        if($social)
        {
            $em = $this->container->get('doctrine')->getManager();
            $em->persist($social);
            $em->flush();
        }

        if ($request->isXmlHttpRequest()) {
            $result = array('success' => true);
			$response = new Response(json_encode($result));
			$response->headers->set('Content-Type', 'application/json');
			return $response;
        } else {
            $referer = $request->headers->get('referer');
            if($referer)
            {
                $url = $referer;
            }
            else
            {
                $url = $this->router->generate('user_perfil');
            }

            return new RedirectResponse($url);
        }
    }

    public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
    {
        if ($request->isXmlHttpRequest()) {
            $result = array('success' => false);
			$response = new Response(json_encode($result));
			$response->headers->set('Content-Type', 'application/json');
			return $response;
        } else {
            $url = $this->router->generate('fos_user_security_login');
			$this->session->getFlashBag()->add('error','Usuario o contraseña incorerctos');
            return new RedirectResponse($url);
        }
    }
}